<template>
  <div class="attendance-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考勤记录管理</span>
        </div>
      </template>

      <div class="search-section">
        <el-form :inline="true" class="search-form">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
            />
          </el-form-item>
          <el-form-item label="成员姓名">
            <el-input v-model="searchName" placeholder="请输入成员姓名" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        :data="attendanceRecords"
        style="width: 100%"
        border
        stripe
        highlight-current-row
      >
        <el-table-column prop="attendanceID" label="记录ID" width="90" align="center" />
        <el-table-column prop="userID" label="用户ID" width="90" align="center" />
        <el-table-column prop="username" label="姓名" width="100" align="center" />
        <el-table-column prop="checkInTime" label="签到时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.checkInTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkOutTime" label="签退时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.checkOutTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status).color"
              effect="light"
              round
            >
              {{ getStatusType(scope.row.status).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="考勤备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="100" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          :model-value="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @update:model-value="handleCurrentChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 编辑考勤弹窗 -->
    <el-dialog
      :title="isEdit ? '编辑考勤' : '新增考勤'"
      v-model="showForm"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form 
        :model="attendanceForm" 
        ref="attendanceForm"
        label-width="100px"
        class="attendance-form"
      >
        <el-form-item label="签到时间">
          <el-date-picker
            v-model="attendanceForm.checkInTime"
            type="datetime"
            placeholder="选择签到时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="签退时间">
          <el-date-picker
            v-model="attendanceForm.checkOutTime"
            type="datetime"
            placeholder="选择签退时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="考勤状态">
          <el-select v-model="attendanceForm.status" placeholder="请选择考勤状态" style="width: 100%">
            <el-option label="正常出勤" value="present" />
            <el-option label="缺勤" value="absent" />
            <el-option label="迟到" value="late" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="attendanceForm.remarks"
            type="textarea"
            rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showForm = false">取消</el-button>
          <el-button type="primary" @click="saveAttendance">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Search, Refresh } from '@element-plus/icons-vue'
import axios from "axios";

export default {
  name: "AttendanceList",
  components: {
    Search,
    Refresh
  },
  data() {
    return {
      dateRange: [],
      searchName: '',
      currentPage: 1,
      pageSize: 10,
      total: 100,
      attendanceRecords: [],
      showForm: false,
      isEdit: false,
      attendanceForm: {
        attendanceID: "",
        userID: "",
        checkInTime: "",
        checkOutTime: "",
        status: "",
        remarks: "",
      },
      dateShortcuts: [
        {
          text: '最近一周',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        },
        {
          text: '最近一月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        }
      ]
    };
  },
  methods: {
    // 返回状态中文和颜色
    getStatusType(status) {
      const statusTypes = {
        'present': { label: '正常出勤', color: 'success' },
        'late': { label: '迟到', color: 'warning' },
        'absent': { label: '缺勤', color: 'danger' },
      };
      return statusTypes[status] || { label: '未知状态', color: 'info' };
    },

    // 获取考勤记录
    fetchAttendance() {
      let startDate = this.dateRange && this.dateRange[0] ? this.dateRange[0] : '';
      let endDate = this.dateRange && this.dateRange[1] ? this.dateRange[1] : '';

      axios
        .get("/attendance/list", {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            startDate: startDate,
            endDate: endDate,
            searchName: this.searchName,
          },
        })
        .then((response) => {
          // 数据返回后处理 username 为 null 的情况
          this.attendanceRecords = response.data.map(record => {
            // 如果用户名为空，给一个默认值
            record.username = record.username || "未知用户";
            return record;
          });
          this.total = response.data.total;
        })
        .catch((error) => {
          console.error("获取考勤记录失败:", error);
        });
    },

    handleSearch() {
      this.fetchAttendance();
    },

    handleReset() {
      this.dateRange = [];
      this.searchName = '';
      this.currentPage = 1;
      this.fetchAttendance();
    },

    handleEdit(row) {
      this.isEdit = true;
      this.attendanceForm = { ...row };
      this.showForm = true;
    },

    saveAttendance() {
      if (this.isEdit) {
        axios
          .put(`/attendance/update/${this.attendanceForm.attendanceID}`, this.attendanceForm)
          .then(() => {
            this.$message.success("考勤记录更新成功");
            this.showForm = false;
            this.fetchAttendance();
          })
          .catch((error) => {
            console.error("更新考勤记录失败:", error);
          });
      } else {
        axios
          .post("/attendance/add", this.attendanceForm)
          .then(() => {
            this.$message.success("考勤记录添加成功");
            this.showForm = false;
            this.fetchAttendance();
          })
          .catch((error) => {
            console.error("添加考勤记录失败:", error);
          });
      }
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchAttendance();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchAttendance();
    },

    // 新增日期格式化方法
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    }
  },

  mounted() {
    this.fetchAttendance();
  },
};
</script>

<style scoped>
.attendance-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  padding: 18px 0;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10pxpx;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item__label) {
  font-weight: normal;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  font-weight: bold;
  color: #606266;
}

.attendance-form {
  padding: 20px 0;
}

:deep(.el-tag) {
  min-width: 60px;
  text-align: center;
}
</style>
